/**
 * API 响应缓存工具
 * 提供基于内存的 API 响应缓存功能
 */

interface CacheItem<T = any> {
  data: T;
  timestamp: number;
  expireTime: number;
}

class ApiCacheManager {
  private cache = new Map<string, CacheItem>();
  private defaultTTL = 5 * 60 * 1000; // 默认5分钟

  /**
   * 生成缓存键
   */
  private generateKey(url: string, params?: any): string {
    const paramsStr = params ? JSON.stringify(params) : '';
    return `${url}_${paramsStr}`;
  }

  /**
   * 设置缓存
   */
  set<T>(url: string, params: any, data: T, ttl?: number): void {
    const key = this.generateKey(url, params);
    const expireTime = ttl || this.defaultTTL;
    
    this.cache.set(key, {
      data,
      timestamp: Date.now(),
      expireTime: Date.now() + expireTime
    });
  }

  /**
   * 获取缓存
   */
  get<T>(url: string, params?: any): T | null {
    const key = this.generateKey(url, params);
    const item = this.cache.get(key);
    
    if (!item) {
      return null;
    }

    // 检查是否过期
    if (Date.now() > item.expireTime) {
      this.cache.delete(key);
      return null;
    }

    return item.data as T;
  }

  /**
   * 删除指定缓存
   */
  delete(url: string, params?: any): boolean {
    const key = this.generateKey(url, params);
    return this.cache.delete(key);
  }

  /**
   * 清空所有缓存
   */
  clear(): void {
    this.cache.clear();
  }

  /**
   * 清理过期缓存
   */
  cleanup(): void {
    const now = Date.now();
    for (const [key, item] of this.cache.entries()) {
      if (now > item.expireTime) {
        this.cache.delete(key);
      }
    }
  }

  /**
   * 获取缓存统计信息
   */
  getStats() {
    return {
      size: this.cache.size,
      keys: Array.from(this.cache.keys())
    };
  }
}

// 创建全局缓存管理器实例
export const apiCache = new ApiCacheManager();

/**
 * 带缓存的API请求包装器
 */
export async function cachedApiRequest<T>(
  requestFn: () => Promise<T>,
  cacheKey: string,
  params?: any,
  ttl?: number
): Promise<T> {
  // 尝试从缓存获取
  const cached = apiCache.get<T>(cacheKey, params);
  if (cached !== null) {
    return cached;
  }

  // 执行实际请求
  const result = await requestFn();
  
  // 存入缓存
  apiCache.set(cacheKey, params, result, ttl);
  
  return result;
}

// 定期清理过期缓存（每10分钟执行一次）
setInterval(() => {
  apiCache.cleanup();
}, 10 * 60 * 1000);